﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Collections;
using DevExpress.XtraGrid.Views.Grid;
using COMOSOFT.Class;
using DevExpress.XtraReports;
using DevExpress.XtraPrinting;
using DevExpress.XtraReports.UI;
using DevExpress.LookAndFeel;
using DevExpress.XtraEditors;

namespace COMOSOFT.OrderBusiness.Forms
{
    public partial class FrmFactoryPurchaseMaster : Form
    {           
        ClassShare cls = new ClassShare("FrmFactoryPurchaseMaster");       
        int FPID;
        bool bAllowModify = false;
        DataTable dtbModify;
        public string OIDS = null;
        public FrmFactoryPurchaseMaster(int _fpid)
        {
            InitializeComponent();
            this.FPID = _fpid;
            if (FPID == -1)
            {
                factoryPurchaseMasterTableAdapter.Fill(dataSetOrderManagement.FactoryPurchaseMaster, FPID);
            }
        }

        #region [AddNew]
        public void NewFPM()
        {           
            factoryPurchaseMasterBindingSource.AddNew();
            groupControl2.Enabled = false;
            dateEdit_issuadate.EditValue = DateTime.Now;
            lookUpEdit_submiter.EditValue = Convert.ToInt64(ClassShare.Usid);
            txt_status.Text = "Waiting";   
        }
        #endregion

        #region[AllowModify]
        private void AllowModify()
        {
            dtbModify=cls.GetData("sp_FtyPurAllowModify", new string[] { "@FPMID","@EID" }, new object[] { FPID,ClassShare.Usid });
            if (dtbModify.Rows.Count > 0)
                bAllowModify = true;
            else
                bAllowModify = false;
        }
        #endregion

        #region [Load Data]
        public void LoadFPM()
        {
            try
            {
                AllowModify();
                factoryListTableAdapter.Fill(this.dataSetOrderManagement.FactoryList);
                employeeTableAdapter.Fill(this.dataSetOrderManagement.Employee);
                sp_GetLeaderManagerTableAdapter.Fill(dataSet_HumanResource.sp_GetLeaderManager);
                if(bAllowModify==false)
                    if (bnt_submit.Text == "Submit")
                        bnt_submit.Enabled = false;
                if (FPID > 0)
                {                    
                    factoryPurchaseMasterTableAdapter.Fill(dataSetOrderManagement.FactoryPurchaseMaster, FPID);
                    sp_FtyPurDetailsViewTableAdapter.Fill(dataSetOrderManagement.sp_FtyPurDetailsView, FPID);
                    groupControl2.Enabled = true;                   
                    gridControl_Factory.Enabled = true;
                    if (bAllowModify == true)
                    {
                        bnt_submit.Enabled = true;
                        contextMenuStrip_addorder.Items[0].Enabled = true;
                        contextMenuStrip_addorder.Items[1].Enabled = true;
                        contextMenuStrip_addorder.Items[2].Enabled = true;                        
                    }
                    else
                    {                        
                        contextMenuStrip_addorder.Items[0].Enabled = false;
                        contextMenuStrip_addorder.Items[1].Enabled = false;
                        contextMenuStrip_addorder.Items[2].Enabled = false;                       
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region [Load PO]
        private void LoadPO()
        {
            DataRow row = gridLookUpEdit1View.GetFocusedDataRow();
            if (row != null && dateEdit_issuadate.EditValue != null && Convert.IsDBNull(dateEdit_issuadate.EditValue)==false)
            {
                try
                {
                    DateTime dt = Convert.ToDateTime(dateEdit_issuadate.EditValue);
                    string date = dt.ToString("yyyy-MM-dd");
                    DataTable dtb = cls.GetData("sp_CheckPONo", new string[2] { "@factory", "@date" }, new object[2] {Convert.ToInt32(row["FLID"]), date });
                    int num = dtb.Rows.Count;
                    if (num > 0 && num < 10)
                    {
                        txt_po.Text = row["FactoryName"].ToString().Replace(" ", "") + Convert.ToDateTime(dateEdit_issuadate.EditValue).ToString("ddMMyyyy") + "0" + (num + 1);
                    }
                    else
                        txt_po.Text = row["FactoryName"].ToString().Replace(" ", "") + Convert.ToDateTime(dateEdit_issuadate.EditValue).ToString("ddMMyyyy") + "01";
                }
                catch
                {
                    MessageBox.Show("Plase try again!");
                }
            }
        }
        private void dateEdit_issuadate_EditValueChanged(object sender, EventArgs e)
        {
            LoadPO();
        }
        private void gridLookUp_factory_EditValueChanged(object sender, EventArgs e)
        {
            LoadPO();
        }
        #endregion

        #region [Update FtyPurMaster - insert FtyPurDetails]
        public void UpdateFPM()
        {
            try
            {
                if (FPID == -1)
                {
                    factoryPurchaseMasterBindingSource.EndEdit();
                    factoryPurchaseMasterTableAdapter.Update(dataSetOrderManagement.FactoryPurchaseMaster);
                    dataSetOrderManagement.FactoryPurchaseMaster.AcceptChanges();
                    if (groupControl2.Enabled == false)
                    {                        
                        FPID = Convert.ToInt32(txt_FPMID.Text);
                        ClassShare.fpid = FPID;
                        groupControl2.Enabled = true;
                        gridControl_Factory.Enabled = true;                       
                        this.Text ="PO:"+ txt_po.Text;
                        if(OIDS != null)
                          cls.UpdateData("sp_FtyPurDetailsInsert", new string[2] { "@OIDs", "@FBID" }, new object[2] { OIDS, FPID });
                        LoadFPM();
                    }
                }
                else
                {
                    if (bAllowModify == true)
                    {
                        factoryPurchaseMasterBindingSource.EndEdit();
                        factoryPurchaseMasterTableAdapter.Update(dataSetOrderManagement.FactoryPurchaseMaster);
                        dataSetOrderManagement.FactoryPurchaseMaster.AcceptChanges();
                    }
                    else
                    {
                        MessageBox.Show("Locked data not modify!");
                    }
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
            }
        }
        #endregion

        #region [Delete FtyPurMaster]
        public void DeleteFtyPurMaster()
        {
            try
            {
                if (bAllowModify == true)
                {
                    if (FPID > 0)
                    {
                        if (XtraMessageBox.Show("Are You Sure Delete Object?", "Question", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                        {
                            cls.UpdateData("sp_FactoryPurchaseMasterDelete", new string[1] { "@FPMID" }, new object[1] { FPID });
                        }
                    }
                }
                else
                {
                    MessageBox.Show("Locked data not modify!");
                }
            }
            catch
            {
                XtraMessageBox.Show("Can't Delete Object!", "Not Delete...!", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
        #endregion

        private void FrmFactoryPurchaseMaster_FormClosing(object sender, FormClosingEventArgs e)
        {
            factoryPurchaseMasterBindingSource.CancelEdit();
        }       

        #region [UpdateFtyPurDetails]
        private void gridView_Factory_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            try
            {
                if (bAllowModify == true)
                {
                    GridView view = sender as GridView;
                    DateTime dtmCusExdate = Convert.ToDateTime(view.GetFocusedDataRow()["CusExDate"]);
                    DateTime dtmFtoryDate = Convert.ToDateTime(view.GetFocusedDataRow()["DeliveryDate"]);

                    if (dtmFtoryDate < dtmCusExdate)
                    {
                        cls.UpdateData("sp_FctPcDetailsUpdate", new string[] { "@FPDID", "@Qty", "@DeliveryDate", "@Remarks" },
                                                                new object[] { Convert.ToInt32(view.GetFocusedDataRow()["FPDID"]), Convert.ToInt16(view.GetFocusedDataRow()["Qty"]), Convert.ToDateTime(view.GetFocusedDataRow()["DeliveryDate"]), view.GetFocusedDataRow()["Remarks"] });
                        sp_FtyPurDetailsViewTableAdapter.Fill(dataSetOrderManagement.sp_FtyPurDetailsView, FPID);
                    }
                    else
                    {
                        MessageBox.Show("The factory date less than the Customer date. Please try again!");
                        sp_FtyPurDetailsViewTableAdapter.Fill(dataSetOrderManagement.sp_FtyPurDetailsView, FPID);
                    }
                }
                else
                {
                    MessageBox.Show("Locked data not modify!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion

        #region [Submit]

        private void bnt_submit_Click(object sender, EventArgs e)
        {
            try
            {               
                if (bnt_submit.Text == "Submit")
                {
                    string fpmids = FPID.ToString().Trim();
                    cls.UpdateData("sp_FtyPurMasterUpdateStatus", new string[3] { "@FPMIDs", "@comment", "@flag" }, new object[3] { fpmids, "", 0 });
                    MessageBox.Show("Submit Successfully!","Submit...",MessageBoxButtons.OK,MessageBoxIcon.Information);
                    this.Close();
                }
                else
                {
                    string OIDs = null;
                    int numrow = gridView_Factory.DataRowCount;
                    for (int i = 0; i < numrow; i++)
                    {
                        if (i == 0)
                            OIDs = gridView_Factory.GetDataRow(i)["OID"].ToString();
                        else
                            OIDs += "," + gridView_Factory.GetDataRow(i)["OID"].ToString();
                    }

                    txt_status.Text = "Approved";
                    factoryPurchaseMasterBindingSource.EndEdit();
                    factoryPurchaseMasterTableAdapter.Update(dataSetOrderManagement.FactoryPurchaseMaster);
                    dataSetOrderManagement.FactoryPurchaseMaster.AcceptChanges();

                    FPID = Convert.ToInt32(txt_FPMID.Text);
                    ClassShare.fpid = FPID;
                    ClassShare.OIDs = OIDs;
                    FrmReport frmRP = new FrmReport("rptOrderDetais");

                    this.AddOwnedForm(frmRP);
                    frmRP.ShowDialog();
                }
            }
            catch
            {
              MessageBox.Show("Don't have orderdetails in factory purchase!","Warnings",MessageBoxButtons.OK,MessageBoxIcon.Warning);
            }
        }
        #endregion

        #region [StatusButton]
        public void StatusButton(string status)
        {
            bnt_submit.Text = status;
            bnt_submit.Image = imageCollection1.Images[0];            
            gridControl_Factory.ContextMenuStrip = null;
        }
        #endregion

        private void gridViewFactory_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {
            try
            {
                factoryListBindingSource.EndEdit();
                factoryListTableAdapter.Update(dataSetOrderManagement.FactoryList);
                dataSetOrderManagement.FactoryList.AcceptChanges();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void gridLookUp_factory_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Tag.ToString() == "Add")
            {
                dockPanel_Factory.Show();
                factoryListTableAdapter.Fill(dataSetOrderManagement.FactoryList);
            }
        }

        #region[ContextMenu]

        private void addOrderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FrmAddOrderFactory frmAOF = new FrmAddOrderFactory(this);
            frmAOF.ShowDialog();
        }

        private void deleteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (bAllowModify == true)
                {
                    if (MessageBox.Show("Are you sure delete?", "Comfirm!", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        int FPDID = Convert.ToInt32(gridView_Factory.GetFocusedDataRow()["FPDID"]);
                        cls.UpdateData("sp_FctPCDetailsDelete", new string[] { "@FPDID" }, new object[] { FPDID });
                        LoadFPM();
                    }
                }
                else
                {
                    MessageBox.Show("Locked data not modify!");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void refreshToolStripMenuItem_Click(object sender, EventArgs e)
        {
            LoadFPM();
        }

        private void submitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                string fpmids = FPID.ToString().Trim();
                cls.UpdateData("sp_FtyPurMasterUpdateStatus", new string[3] { "@FPMIDs", "@comment", "@flag" }, new object[3] { fpmids, "", 0 });
                MessageBox.Show("Submit Successfully!", "Submit...", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        #endregion    
    }
}